package com.itheima.controller;

import com.itheima.pojo.Supplier;
import com.itheima.qo.PageQuery;
import com.itheima.vo.PageResult;
import com.itheima.vo.Result;
import com.itheima.service.CityService;
import com.itheima.service.SupplierService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Map;

@RestController
@RequestMapping("/supplier")
public class SupplierController {

    @Autowired
    private SupplierService supplierService;

    @Autowired
    private CityService cityService;

    /**
     * 分页查询供应商列表
     */
    @PostMapping("/page")
    public Result page(@RequestBody Map<String, Object> params) {
        // 从参数中提取分页信息
        PageQuery pageQuery = new PageQuery();
        if (params.get("page") != null) {
            pageQuery.setPage((Integer) params.get("page"));
        }
        if (params.get("pageSize") != null) {
            pageQuery.setPageSize((Integer) params.get("pageSize"));
        }
        
        PageResult pageResult = supplierService.pageByMap(pageQuery, params);
        return Result.success(pageResult);
    }

    /**
     * 获取供应商列表
     */
    @GetMapping("/list")
    public Result list() {
        return Result.success(supplierService.listAll());
    }

    /**
     * 根据ID查询供应商
     */
    @GetMapping("/{id}")
    public Result getById(@PathVariable Integer id) {
        Supplier supplier = supplierService.getById(id);
        return Result.success(supplier);
    }

    /**
     * 添加供应商
     */
    @PostMapping
    public Result add(@RequestBody Supplier supplier) {
        supplierService.save(supplier);
        return Result.success();
    }

    /**
     * 更新供应商
     */
    @PutMapping
    public Result update(@RequestBody Supplier supplier) {
        supplierService.update(supplier);
        return Result.success();
    }

    /**
     * 删除供应商
     */
    @DeleteMapping("/{id}")
    public Result delete(@PathVariable Integer id) {
        supplierService.deleteById(id);
        return Result.success();
    }

    /**
     * 获取城市列表（省市区树形结构）
     */
    @GetMapping("/city")
    public Result getCityList() {
        return Result.success(cityService.listAll());
    }
}